﻿using System;
using System.Net;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace MS.InformationManagement.DocumentIDServiceApp.Admin
{
    public partial class DocumentIDServiceCreate : LayoutsPageBase
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ((DialogMaster)this.Page.Master).OkButton.Click += new EventHandler(this.OkButton_Click);
        }

        protected void OkButton_Click(object sender, EventArgs e)
        {
            if (SPUtility.ValidateFormDigest() && this.Page.IsValid)
            {
                if (this.ApplicationId == Guid.Empty)
                {
                    this.CreateServiceApp();
                }
                this.SendResponseForPopUI();
            }
        }

        private void CreateServiceApp()
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.Begin();
                try
                {
                    string name = this.m_asAppName.Text.Trim();

                    // Ensure that the farm level required objects exist
                    SPFarm farm = SPFarm.Local;
                    if (null == farm)
                    {
                        throw new InvalidOperationException("SharePoint server farm not found.");
                    }

                    // Ensure that the Protocol Service exists
                    DocumentIDService service = farm.Services.GetValue<DocumentIDService>("DocumentIDService");
                    if (service == null)
                    {
                        throw new InvalidOperationException("DocumentIDService Service not found.");
                    }

                    // Check for an existing Protocol Service Application
                    DocumentIDServiceApplication existingServiceApplication = service.Applications.GetValue<DocumentIDServiceApplication>();
                    if (existingServiceApplication != null)
                    {
                        throw new InvalidOperationException("DocumentIDService Service Application exists.");
                    }

                    // Get a reference to the specified application pool
                    SPIisWebServiceApplicationPool applicationPool = ((IisWebServiceApplicationPoolSection)this.m_applicationPoolSection).GetOrCreateApplicationPool();
                    if (applicationPool == null)
                    {
                        throw new InvalidOperationException("The specified application pool could not be found.");
                    }

                    String databaseName = ((ContentDatabaseSection)this.ProtocolServiceAppDBSection).DatabaseName;
                    String databaseServer = ((ContentDatabaseSection)this.ProtocolServiceAppDBSection).DatabaseServer;
                    String databaseFailoverServer = ((ContentDatabaseSection)this.ProtocolServiceAppDBSection).FailoverDatabaseServer;
                    String databaseUserName = ((ContentDatabaseSection)this.ProtocolServiceAppDBSection).DatabaseUserName;
                    String databasePassword = ((ContentDatabaseSection)this.ProtocolServiceAppDBSection).DatabasePassword;

                    // Construct parameters for new database
                    SPDatabaseParameters databaseParameters = SPDatabaseParameters.CreateParameters(
                        databaseName,
                        databaseServer,
                        new NetworkCredential(databaseUserName, databasePassword),
                        databaseFailoverServer,
                        SPDatabaseParameterOptions.ResolveNameConflict | SPDatabaseParameterOptions.GenerateUniqueName);

                    // Create the sample application
                    DocumentIDServiceApplication serviceApplication = DocumentIDServiceApplication.Create(
                        name, service, applicationPool, databaseParameters);

                    if (serviceApplication == null)
                        throw new NullReferenceException("DocumentIDServiceApplication");

                    // Provision the sample application
                    serviceApplication.Provision();

                    // Create the service application proxy
                    DocumentIDServiceApplicationProxy proxy = (DocumentIDServiceApplicationProxy)DocumentIDService.CurrentInstance.CreateProxy(name, serviceApplication, null);
                    proxy.Update(true);
                    proxy.Provision();
                    if (this.m_default.Checked)
                    {
                        proxy.AddToDefaultGroup();
                    }
                }
                catch (Exception ex)
                {
                    throw new SPException("Failed to create service applicaton", ex);
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.Page.IsPostBack)
            {
                Guid applicationId = this.ApplicationId;
                if (applicationId != Guid.Empty)
                {
                    if (SPFarm.Local == null)
                    {
                        throw new NullReferenceException("SPFarm.Local");
                    }

                    DocumentIDServiceApplication application =
                        SPFarm.Local.GetObject(applicationId) as DocumentIDServiceApplication;

                    if (application != null)
                    {
                        this.m_asAppName.Text = application.Name;
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
            }
        }

        protected void ValidateUniqueName(object sender, ServerValidateEventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
            if (SPFarm.Local == null)
            {
                throw new NullReferenceException("SPFarm.Local");
            }

            string name = this.m_asAppName.Text.Trim();
            DocumentIDServiceApplication applicationByName = DocumentIDServiceApplication.GetLocalApplicationByName(name);
            bool flag = true;
            if (applicationByName != null)
            {
                flag = false;
            }
            e.IsValid = flag;
            this.m_uniqueNameValidator.ErrorMessage = "The specified service application name is already in use.";
        }

        // Properties
        private Guid ApplicationId
        {
            get
            {
                Guid result = Guid.Empty;
                if (base.Request.QueryString != null)
                {
                    string str = base.Request.QueryString["appid"];
                    if (string.IsNullOrEmpty(str))
                    {
                        return result;
                    }
                    try
                    {
                        result = new Guid(str);
                    }
                    catch (FormatException)
                    {
                        throw new Exception();
                    }
                }
                return result;
            }
        }
    }
}
